﻿package com.location;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.GeofenceClient;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;

import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;

public class LocateFunc {
	private LocationClient mLocationClient;
	private MyLocationListener mMyLocationListener;
	public String pvTime ;  //拍摄资源的时间
	private StringBuffer pvAddress = new StringBuffer(256);  //拍摄资源的地点
	private Context context;
	private Handler handler;
	 

	public LocateFunc(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		mLocationClient = new LocationClient(this.context);
		mMyLocationListener = new MyLocationListener();
		mLocationClient.registerLocationListener(mMyLocationListener);
		InitLocation();
		mLocationClient.start();
	}

	public void requestlocation() {
		if (mLocationClient != null && mLocationClient.isStarted()) {
			mLocationClient.requestLocation();
		}
	}

	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);// 设置定位模式
		option.setOpenGps(true);
		int span = 999;
		option.setScanSpan(span);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
	}

	/**
	 * 实现实位回调监听
	 */
	public class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// Receive Location
			pvTime = location.getTime();
			if (location.getLocType() == BDLocation.TypeGpsLocation) {
				//GPS模式
				pvAddress = pvAddress.append(location.getAddrStr());
				
			} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
				//各个地区级别之间以","隔开
				pvAddress.append(location.getProvince()).append(",");
				pvAddress.append(location.getCity()).append(",");
				pvAddress.append(location.getDistrict()).append(",");
				pvAddress.append(location.getStreet());
			}
			sendMsg(pvAddress.toString());
		}
	}

	/**
	 * 传送字符串
	 */
	public void sendMsg(String strPvAddress) {

		//这个信息是地点
		Message pvAddressMsg = new Message();
		pvAddressMsg.what = 0;
		pvAddressMsg.obj = strPvAddress;
		handler.sendMessage(pvAddressMsg);
		
		//这个信息是时间相关
		Message pvTimeMsg = new Message();
		pvTimeMsg.what = 1;
		pvTimeMsg.obj = pvTime;
		handler.sendMessage(pvTimeMsg);
		
		//停止这个客户端
		mLocationClient.stop();
	}

}
